package Task24;

import java.io.IOException;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class MySAXParser extends DefaultHandler {

	private ArrayList<String> data = new ArrayList<String>();
	private String tempVal;
	private String lastQName;
	private String fileWithDir;
	private int level = 0;

	public MySAXParser(String file) {
		fileWithDir = file;
		parseDocument();
	}

	public ArrayList<String> getResult() {
		return data;
	}

	private void parseDocument() {

		// get a factory
		SAXParserFactory spf = SAXParserFactory.newInstance();
		try {

			// get a new instance of parser
			SAXParser sp = spf.newSAXParser();

			// parse the file and also register this class for call backs
			sp.parse(fileWithDir, this);

		} catch (SAXException se) {
			se.printStackTrace();
		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		} catch (IOException ie) {
			ie.printStackTrace();
		}
	}

	// Event Handlers
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// reset

		String sAtr = "";
		for (int i = 0; i < attributes.getLength(); i++) {
			String name = attributes.getLocalName(i);
			String value = attributes.getValue(i);

			sAtr += " " + name + "=" + value + " ";
		}

		data.add(getShift()+"<" + qName + sAtr + ">");
		tempVal = "";
		lastQName = qName;
		level++;
	}

	public void characters(char[] ch, int start, int length)
			throws SAXException {
		tempVal = new String(ch, start, length);

	}

	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (lastQName.equalsIgnoreCase(qName)) {
			String lastValue = data.remove(data.size() - 1);
			data.add(lastValue + tempVal + "</" + qName + ">");
			level--;
		} else {
			level--;
			data.add(getShift()+"</" + qName + ">");
		}
	}
	
	private String getShift(){
		String shift = "";
		for (int i = 0; i < level; i++)
			shift += "   ";
		return shift;
	}
}
